/**
 * 统一的HTTP请求工具
 * 自动携带baseUrl和token，统一错误处理
 */
import { http } from "@/common/service/service.js";

class HttpUtil {
  /**
   * GET请求
   * @param {string} url - 请求路径
   * @param {object} params - 请求参数
   * @param {object} options - 其他配置
   */
  static async get(url, params = {}, options = {}) {
    try {
      const response = await http.get(url, params, options);
      return this.handleResponse(response);
    } catch (error) {
      return this.handleError(error);
    }
  }

  /**
   * POST请求
   * @param {string} url - 请求路径
   * @param {object} data - 请求数据
   * @param {object} options - 其他配置
   */
  static async post(url, data = {}, options = {}) {
    try {
      const response = await http.post(url, data, options);
      return this.handleResponse(response);
    } catch (error) {
      return this.handleError(error);
    }
  }

  /**
   * PUT请求
   * @param {string} url - 请求路径
   * @param {object} data - 请求数据
   * @param {object} options - 其他配置
   */
  static async put(url, data = {}, options = {}) {
    try {
      const response = await http.put(url, data, options);
      return this.handleResponse(response);
    } catch (error) {
      return this.handleError(error);
    }
  }

  /**
   * DELETE请求
   * @param {string} url - 请求路径
   * @param {object} params - 请求参数
   * @param {object} options - 其他配置
   */
  static async delete(url, params = {}, options = {}) {
    try {
      const response = await http.delete(url, params, options);
      return this.handleResponse(response);
    } catch (error) {
      return this.handleError(error);
    }
  }

  /**
   * 文件上传
   * @param {string} url - 上传路径
   * @param {object} filePath - 文件路径
   * @param {object} formData - 表单数据
   */
  static async upload(url, filePath, formData = {}) {
    try {
      const response = await http.upload(url, {
        filePath,
        formData,
        name: 'file'
      });
      return this.handleResponse(response);
    } catch (error) {
      return this.handleError(error);
    }
  }

  /**
   * 处理响应数据
   * @param {object} response - 响应对象
   */
  static handleResponse(response) {
    const { data } = response;
    
    // JeecgBoot标准响应格式处理
    if (data.success === false) {
      throw new Error(data.message || '请求失败');
    }
    
    return {
      success: true,
      data: data.result || data,
      message: data.message || '操作成功',
      code: data.code || 200
    };
  }

  /**
   * 处理错误
   * @param {object} error - 错误对象
   */
  static handleError(error) {
    console.error('HTTP请求错误:', error);
    
    let message = '网络错误，请重试';
    if (error.message) {
      message = error.message;
    } else if (error.data && error.data.message) {
      message = error.data.message;
    }
    
    return {
      success: false,
      data: null,
      message,
      code: error.statusCode || 500
    };
  }

  /**
   * 批量请求
   * @param {Array} requests - 请求数组
   */
  static async batch(requests) {
    try {
      const promises = requests.map(req => {
        const { method, url, data, params } = req;
        switch (method.toLowerCase()) {
          case 'get':
            return this.get(url, params);
          case 'post':
            return this.post(url, data);
          case 'put':
            return this.put(url, data);
          case 'delete':
            return this.delete(url, params);
          default:
            throw new Error(`不支持的请求方法: ${method}`);
        }
      });
      
      const results = await Promise.allSettled(promises);
      return results.map(result => {
        if (result.status === 'fulfilled') {
          return result.value;
        } else {
          return this.handleError(result.reason);
        }
      });
    } catch (error) {
      return [this.handleError(error)];
    }
  }
}

export default HttpUtil;
